import { useMemo, useState, useRef, useImperativeHandle, forwardRef } from 'react'
import { message, Table, Modal } from 'antd';
import Pagination from '@inbiz/basic/Pagination';
import { TextWidget } from '@inbiz/react';
import { uuid } from '@inbiz/utils';
import LangView from '@inbiz/basic/LangView';
import { getLangList, deleteLanguages, getComponentsLangList, getFormLangList, deleteFormLang } from '../service';
import { formatSiteType, formatQueryFormData } from '../utils';
const { confirm } = Modal;

const QueryTable = forwardRef((props: any, ref) => {
    const {
        pageOutId,
        queryLanguageType,
        isApp,
        isForm,
        editLang,
        queryBarRef,
        components,
        allLangs,
        selectedRowKeys,
        setSelectedRowKeys,
    } = props;
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<any[]>([]);
    const [pageIndex, setPageIndex] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [visible, setVisible] = useState(false);
    const [editCode, setEditCode] = useState('');

    const formQueryDataRef = useRef<any>({});

    const init = () => {
        setTotal(0);
        setData([]);
        setLoading(false);
    };

    const getLangData = async (queryParams?: any, _pageSize?: number, _pageIndex?: number) => {
        try {
            setLoading(true);
            const _isForm = queryParams?.isForm;
            const _queryParams = { ...queryParams };
            formQueryDataRef.current = { ...queryParams };
            setPageSize(_pageSize || 10);
            setPageIndex(_pageIndex || 1);
            let results: any = {};
            delete _queryParams?.queryLanguageType;
            delete _queryParams.isForm;
            if (queryParams?.queryLanguageType == '0') {
                if (_isForm) {
                    results = await getFormLangList({
                        maxResultCount: _pageSize ?? 10,
                        skipCount: ((_pageSize || _pageSize == 0) && _pageIndex) ? (_pageIndex - 1) * _pageSize : 0,
                        ..._queryParams,
                    });
                } else {
                    results = await getLangList({
                        maxResultCount: _pageSize ?? 10,
                        skipCount: ((_pageSize || _pageSize == 0) && _pageIndex) ? (_pageIndex - 1) * _pageSize : 0,
                        ..._queryParams,
                    });
                };
            } else {
                results = await getComponentsLangList({
                    maxResultCount: _pageSize ?? 10,
                    skipCount: ((_pageSize || _pageSize == 0) && _pageIndex) ? (_pageIndex - 1) * _pageSize : 0,
                    ..._queryParams,
                });
            };
            const _dataItems = results?.Items;
            if (_dataItems?.length == 0 || !results) {
                init();
                return;
            };
            setTotal(results?.TotalCount);
            let langData: any[] = []
            if (queryParams?.queryLanguageType == '0') {
                langData = results?.Items?.map((item: any) => {
                    let langObject: any = {};
                    item?.Kinds?.map((item: { KindCode: string; LangText: string; }) => {
                        langObject[item?.KindCode] = item?.LangText
                    });
                    return {
                        Key: item?.Key || uuid(20, 60),
                        SiteType: item?.SiteType,
                        ComponentName: item?.ComponentName || item?.Code || '',
                        ComponentLangType: item?.ComponentLangType || '',
                        ...langObject,
                    };
                });
            } else {
                langData = results?.Items?.map((item: any) => {
                    return {
                        Key: item?.Key || uuid(20, 60),
                        Code: item?.Code,
                    };
                });
            };
            setData(langData);
            setLoading(false);
        } catch (error: any) {
            message.error(error);
            init();
        }
    };

    const opCallbackAfterAdd = () => {
        getLangData({
            dataVersionId: formQueryDataRef.current?.dataVersionId || '',
            siteOutId: formQueryDataRef.current?.siteOutId || '',
            siteType: formQueryDataRef.current?.siteType || '',
            isForm: false,
            queryLanguageType: '0',
        });
    };

    const opCallback = () => {
        getLangData({ ...formatQueryFormData(queryBarRef?.current?.queryForm?.getFieldsValue()), ...formQueryDataRef.current });
    };

    const onDelete = (keys: string | string[]) => {
        confirm({
            content: '确认删除吗？',
            onOk: async () => {
                const result = await (isForm ? deleteFormLang : deleteLanguages)({ key: typeof keys == 'string' ? [keys] : keys });
                if (result === true) {
                    opCallback();
                    message.success('删除成功');
                };
            },
        });
    };

    const onComponentEdit = (code: string) => {
        setEditCode(code);
        setVisible(true);
    };

    const columns = useMemo(() => {
        const _langColumns = allLangs?.map((item: { Name: string; Code: string; }) => {
            return {
                title: item?.Name || '',
                dataIndex: item?.Code || '',
                key: item?.Code || '',
                ellipsis: true,
                width: 200,
            };
        });
        switch (queryLanguageType) {
            case '0':
                if (isForm) {
                    return [
                        {
                            title: '唯一标识',
                            dataIndex: 'Key',
                            key: 'Key',
                            width: 200,
                            ellipsis: true,
                            fixed: 'left',
                        },
                        ..._langColumns,
                        {
                            title: '操作',
                            key: 'op',
                            dataIndex: 'op',
                            width: isApp ? 100 : 70,
                            fixed: 'right',
                            render: (t: any, r: any) => {
                                return (
                                    <>
                                        <a style={{ marginRight: 10 }} onClick={() => { editLang({ ...r, _langType: queryLanguageType }) }}>编辑</a>
                                        {
                                            isApp && <a style={{ color: 'var(--inbiz-color-primary)' }} onClick={() => { onDelete(r?.Key) }}>删除</a>
                                        }
                                    </>
                                )
                            },
                        },
                    ];
                } else {
                    return [
                        {
                            title: '唯一标识',
                            dataIndex: 'Key',
                            key: 'Key',
                            width: 200,
                            ellipsis: true,
                            fixed: 'left',
                        },
                        ..._langColumns,
                        {
                            title: '所属',
                            key: 'SiteType',
                            dataIndex: 'SiteType',
                            ellipsis: true,
                            width: 180,
                            fixed: 'right',
                            render: (t: number) => formatSiteType(t),
                        },
                        {
                            title: '操作',
                            key: 'op',
                            dataIndex: 'op',
                            width: isApp ? 100 : 70,
                            fixed: 'right',
                            render: (t: any, r: any) => {
                                return (
                                    <>
                                        <a style={{ marginRight: 10 }} onClick={() => { editLang({ ...r, _langType: queryLanguageType }) }}>编辑</a>
                                        {
                                            isApp && <a style={{ color: 'var(--inbiz-color-primary)' }} onClick={() => { onDelete(r?.Key) }}>删除</a>
                                        }
                                    </>
                                )
                            },
                        },
                    ];
                }
            case '1':
                return [
                    {
                        title: '序号',
                        dataIndex: 'Key',
                        key: 'Key',
                        width: 100,
                        render: (t: string, r: any, i: number) => {
                            return (pageIndex - 1) * pageSize + i + 1;
                        }
                    },
                    {
                        title: '组件',
                        dataIndex: 'Code',
                        key: 'Code',
                        ellipsis: true,
                        render: (t: string) => components?.find((item: { key: string; }) => item?.key == t)?.name
                            ?
                            <TextWidget>{components?.find((item: { key: string; }) => item?.key == t)?.name}</TextWidget>
                            :
                            t,
                    },
                    {
                        title: '操作',
                        key: 'op',
                        dataIndex: 'op',
                        width: 70,
                        render: (t: any, r: any) => {
                            return (
                                <a style={{ marginRight: 10 }} onClick={() => { onComponentEdit(r?.Code) }}>编辑</a>
                            )
                        },
                    },
                ];
            default:
                return [];
        };
    }, [queryLanguageType, components, allLangs, isApp, pageIndex, pageSize, isForm]);

    useImperativeHandle(ref, () => {
        return {
            getLangData,
            onDelete,
            setData,
            setTotal,
            formQueryData: formQueryDataRef?.current || {},
            opCallback,
            opCallbackAfterAdd,
        };
    });

    return (
        <div className='inbiz-lang-manage-query-table'>
            {
                (isApp && queryLanguageType == '0')
                    ?
                    <Table
                        columns={columns}
                        dataSource={data}
                        size='middle'
                        bordered
                        rowKey={'Key'}
                        loading={loading}
                        pagination={false}
                        scroll={data?.length == 0 ? {} : { x: '100%', y: 470 }}
                        rowSelection={{
                            type: 'checkbox',
                            selectedRowKeys,
                            onChange: (selectedRowKeys: any[]) => {
                                setSelectedRowKeys(selectedRowKeys);
                            },
                        }}
                    />
                    :
                    <Table
                        columns={columns}
                        dataSource={data}
                        size='middle'
                        bordered
                        rowKey={'Key'}
                        loading={loading}
                        pagination={false}
                        scroll={data?.length == 0 ? {} : { x: '100%', y: 470 }}
                    />
            }
            <Pagination
                pagination={{
                    current: pageIndex,
                    pageSize: pageSize,
                    total: total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    pageSizeOptions: [10, 20, 30, 50, 100],
                    // @ts-ignore
                    showTotal: true,
                }}
                onPageChange={(current: { current: number; pageSize: number }) => {
                    getLangData(formatQueryFormData(formQueryDataRef?.current), current.pageSize, current.current);
                }}
            />
            {
                visible
                &&
                <LangView
                    visible={visible}
                    langs={allLangs}
                    pageOutId={pageOutId}
                    code={editCode}
                    onCancel={() => {
                        setVisible(false);
                    }}
                    onOk={() => {
                        setVisible(false);
                    }}
                />
            }
        </div>
    )
});

export default QueryTable;